﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace NETCommon.Domain
{
    public class NDomainManager
    {
        private String startupPath;
        private String cachePath;
        private string configFile;
        private AppDomain m_Domain;
        public NDomainManager()
        {
            startupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            cachePath = Path.Combine(startupPath, "__cache");
        }
        public void LoadDomain(String DomainName)
        {
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationName = "ScriptEngine";
            setup.ShadowCopyFiles = "true";		// note: it isn't a bool
            setup.CachePath = cachePath;
            setup.ShadowCopyDirectories = AppDomain.CurrentDomain.BaseDirectory;

            // Create the application domain. The evidence of this
            // running assembly is used for the new domain:
            m_Domain = AppDomain.CreateDomain(DomainName, AppDomain.CurrentDomain.Evidence, setup);

        }
        public NDomainLoader CreateLoader()
        {
            return (NDomainLoader)m_Domain.CreateInstanceAndUnwrap(typeof(NDomainLoader).Assembly.FullName, typeof(NDomainLoader).FullName);
        }
        public void UnloadDomain()
        {          


            if (m_Domain != null)
            {
                AppDomain.Unload(m_Domain);
                Directory.Delete(cachePath, true);
            }
        }

    }
}
